package com.yichi.detector;

import static com.yichi.detector.HeadPoseDetector.*;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.google.mlkit.vision.face.Face;
import com.google.mlkit.vision.face.FaceLandmark;

import java.util.concurrent.Executor;

public class LiveDetector {
    private final String TAG = "LiveDetector";

    private LivenessCallback callback;
    // 三大检测模式
    private final BlinkDetector blinkDetector = new BlinkDetector();
    private final HeadPoseDetector headPoseDetector = new HeadPoseDetector();
    private final Executor mainExecutor;
    private Context context;
    // 增加静态检测器
    private final StaticImageDetector staticDetector = new StaticImageDetector();
    private static final float POSITION_THRESHOLD = 0.25f; // 允许25%的偏移
    private int frameWidth = 0;
    private int frameHeight = 0;
    private long lastFrameTimestamp = 0;
    private volatile boolean isDetectionActive = true;
    public void release() {
        resetDetection();
    }

    private DetectionStage currentStage = DetectionStage.BLINK_CHECK;


    // 修改构造函数
    public LiveDetector(@NonNull Context context,
                        @NonNull LivenessCallback callback) {
        this.callback = callback;
        this.context = context;
        this.mainExecutor = ContextCompat.getMainExecutor(context);

    }

    public void analyze(Face face, Bitmap rgb) {
        if (!isDetectionActive) {
            Log.d(TAG, "检测已停止，忽略本帧");
            return;
        }
        if (System.currentTimeMillis() - lastFrameTimestamp < 500) {
            Log.d(TAG, "检测频率过快，跳过本帧");
            return;
        }

        if (face == null) {
            Log.d(TAG, "未检测到人脸，跳过本帧");
            return;
        }
        if (face.getLandmark(FaceLandmark.LEFT_EYE) == null
                || face.getLandmark(FaceLandmark.RIGHT_EYE) == null
                || face.getLandmark(FaceLandmark.NOSE_BASE) == null
                || face.getLandmark(FaceLandmark.MOUTH_BOTTOM) == null
                || face.getLandmark(FaceLandmark.MOUTH_RIGHT) == null
                || face.getLandmark(FaceLandmark.MOUTH_LEFT) == null
                || face.getLandmark(FaceLandmark.RIGHT_CHEEK) == null
                || face.getLandmark(FaceLandmark.LEFT_CHEEK) == null) {
            Log.d(TAG, "未检测到人脸，跳过本帧");
            return;
        }

        if (face.getTrackingId() == null) {
            Log.d(TAG, "未检测到人脸，跳过本帧");
            return;
        }

        if (!isFaceCentered(face)) {
            callback.onStatusUpdate(-1, "请将人脸置于画面中心");
            return;
        }
        lastFrameTimestamp = System.currentTimeMillis();
        updateGuidance(face); // 新增实时提示
        onAllChecksPassed(rgb);

//        switch (currentStage) {
//            case BLINK_CHECK:
//                if (blinkDetector.checkBlink(face)) {
//                    callback.onStatusUpdate(currentStage.getCode(), "请面向屏幕");
//                    advanceStage();
//                    blinkDetector.reset();
//                }
//                break;
////            case HEAD_MOVEMENT_LEFT:
////                if (headPoseDetector.validateHeadMovement(face, Action.LEFT)) {
////                    callback.onStatusUpdate(currentStage.getCode(), "请缓慢向右转头");
////                    advanceStage();
////                    headPoseDetector.reset();
////                }
////                break;
////            case HEAD_MOVEMENT_RIGHT:
////                if (headPoseDetector.validateHeadMovement(face, Action.RIGHT)) {
////                    callback.onStatusUpdate(currentStage.getCode(), "活体检验成功");
////                    advanceStage();
////                    headPoseDetector.reset();
////                }
////                break;
//            case FINISH:
//                onAllChecksPassed(rgb);
//                break;
//        }
    }

    private boolean isFaceCentered(Face face) {
        // 获取多个关键特征点
        FaceLandmark nose = face.getLandmark(FaceLandmark.NOSE_BASE);
        FaceLandmark leftEye = face.getLandmark(FaceLandmark.LEFT_EYE);
        FaceLandmark rightEye = face.getLandmark(FaceLandmark.RIGHT_EYE);
        FaceLandmark mouthLeft = face.getLandmark(FaceLandmark.MOUTH_LEFT);
        FaceLandmark mouthRight = face.getLandmark(FaceLandmark.MOUTH_RIGHT);
        FaceLandmark mouthBottom = face.getLandmark(FaceLandmark.MOUTH_BOTTOM);

        // 1. 基础检查
        if (nose == null || leftEye == null || rightEye == null
                || mouthLeft == null || mouthRight == null || mouthBottom == null) {
            return false;
        }

        // 2. 计算面部特征中心点
        PointF nosePos = nose.getPosition();
        PointF leftEyePos = leftEye.getPosition();
        PointF rightEyePos = rightEye.getPosition();
        PointF mouthCenter = new PointF(
                (mouthLeft.getPosition().x + mouthRight.getPosition().x) / 2,
                (mouthBottom.getPosition().y + mouthBottom.getPosition().y) / 2
        );
        // 3. 多特征点综合判断
        return isPositionCentered(nosePos.x, nosePos.y) &&
                isPositionCentered(leftEyePos.x, leftEyePos.y) &&
                isPositionCentered(rightEyePos.x, rightEyePos.y) &&
                isPositionCentered(mouthCenter.x, mouthCenter.y);
    }

    private boolean isPositionCentered(float x, float y) {
        if (frameWidth == 0 || frameHeight == 0) return true;

        // 计算中心区域边界
        float centerX = frameWidth / 2f;
        float centerY = frameHeight / 2f;
        float xThreshold = frameWidth * POSITION_THRESHOLD;
        float yThreshold = frameHeight * POSITION_THRESHOLD;

        return Math.abs(x - centerX) < xThreshold &&
                Math.abs(y - centerY) < yThreshold;
    }

    private void updateGuidance(Face face) {
        if (currentStage == DetectionStage.HEAD_MOVEMENT_LEFT ||
                currentStage == DetectionStage.HEAD_MOVEMENT_RIGHT) {

            float yaw = face.getHeadEulerAngleY();
            float progress = Math.abs(yaw) / 25f * 100;
            callback.onProgressUpdate(progress);
        }
    }

    private void onAllChecksPassed(Bitmap rgb) {
        try {
            // 最终验证
            callback.onLiveSuccess(rgb);
            resetDetection();

        } catch (Exception e) {
            handleException(e);
        }
    }


    private void handleException(Exception e) {
        Log.e(TAG, "检测异常", e);
        mainExecutor.execute(() ->
                callback.onError("检测系统错误: " + e.getMessage()));
    }

    private void resetDetection() {
        currentStage = DetectionStage.BLINK_CHECK;
        // 重置所有检测器状态
        blinkDetector.reset();
        headPoseDetector.reset();
        staticDetector.reset();
    }

    private void advanceStage() {
//        currentStage = DetectionStage.values()[currentStage.ordinal() + 1];
        currentStage = DetectionStage.FINISH;
    }

    public interface LivenessCallback {
        // 活体检测成功
        void onLiveSuccess(Bitmap verifiedFace);

        // 状态更新提示
        void onStatusUpdate(int code, String message);

        // 错误通知
        void onError(String error);

        // 检测进度更新（可选）
        default void onProgressUpdate(float progress) {
        }
    }


    // 新增停止检测方法
    public void stopDetection() {
        isDetectionActive = false;
        resetDetection();
        Log.d(TAG, "检测已立即停止");
    }

    public boolean isStopDetection() {
        return isDetectionActive;
    }

    public void startDetection() {
        isDetectionActive = true;
    }

    public void setCallback(LivenessCallback callback){
        this.callback = callback;
    }

}
